﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Surpass.Model.SysDomain;
using Surpass.Model.WorkFlow;

namespace Surpass.Repository.Repository
{
    public class SurpassDbContext : DbContext
    {
        public SurpassDbContext(DbContextOptions<SurpassDbContext> dbContext):base(dbContext)
        {
           
        }
        public DbSet<SysDept> SysDept { get; set; }

        public DbSet<SysUser> SysUsers { get; set; }
        public DbSet<SysRole> SysRoles { get; set; }
        public DbSet<SysMenu> SysMenus { get; set; }
        public DbSet<FlowInstance> FlowInstances { get; set; }
        public DbSet<FlowRecord> FlowRecord { get; set; }
        public DbSet<Node> Nodes { get; set; }
        public DbSet<LeaveRequest> LeaveRequest { get; set; }
        public DbSet<SysUserRoleRelation> SysUserRoleRelations { get; set; }
        public DbSet<SysRoleMenuRelation> SysRoleMenuRelations { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            
            modelBuilder.Entity<SysUser>().HasIndex(c => new {  c.UserId });
            modelBuilder.Entity<SysUser>().HasIndex(c => c.Email).IsUnique();

            modelBuilder.Entity<SysRole>().HasIndex(c => new {  c.RoleId });

            modelBuilder.Entity<SysUserRoleRelation>()
                .HasKey(t => new { t.RoleId, t.UserId });
            modelBuilder.Entity<SysUserRoleRelation>()
                .HasOne(ur => ur.SysUser)
                .WithMany(r => r.SysUserRoleRelations)
                .HasForeignKey(c => c.UserId);
            modelBuilder.Entity<SysUserRoleRelation>()
                .HasOne(ur => ur.SysRole)
                .WithMany(r => r.SysUserRoleRelations)
                .HasForeignKey(c => c.RoleId);

            modelBuilder.Entity<SysRoleMenuRelation>()
                .HasKey(t => new { t.RoleId, t.MenuId });
            modelBuilder.Entity<SysRoleMenuRelation>()
                .HasOne(rm => rm.SysRole)
                .WithMany(r => r.SysRoleMenuRelations)
                 .HasForeignKey(c => c.RoleId);
            modelBuilder.Entity<SysRoleMenuRelation>()
                .HasOne(rm => rm.SysMenu)
                .WithMany(r => r.SysRoleMenuRelations)
                .HasForeignKey(c => c.MenuId);

            // 初始数据
            modelBuilder.InitData();
        }
    }
}
